//
//  ICMAppointmentMaintenanceAndPartsView.m
//  ICrEAM
//
//  Created by Cty on 2016/11/03.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMAppointmentMaintenanceAndPartsView.h"
#import "ICMGetCarRepairPartsTableViewCell.h"
#import "ICMGetCarRepairEventTableViewCell.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMRepairPartsModel.h"
#import "ICMTitleTextFeildView.h"
#import "ICMRepairEventAndPartSearchViewController.h"
#import "ICMPartsTopModel.h"

#define xInset                      ActualWidth(20)
#define xDistance                   ActualWidth(25)
#define yDistance                   ActualHeight(10)
#define TitleTFViewHeight           ActualHeight(63)

@interface ICMAppointmentMaintenanceAndPartsView ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,ICMGetCarRepairEventTableViewCellDelegate,ICMGetCarRepairPartsTableViewCellDelegate,ICMRepairEventAndPartSearchViewControllerDelegate>

@property (nonatomic, strong) NSString *selectedRepairType;

@property (nonatomic, strong) UITableView *repairEventTableView;

@property (nonatomic, strong) UITableView *repairPartsTableView;

@property (nonatomic, strong) UIView *repairTypeSelectionView;

@property (nonatomic, strong) TPKeyboardAvoidingScrollView *backgroundScrollView;

@property (nonatomic, strong) ICMRepairEventAndPartSearchViewController *reapsvc;

@property (nonatomic, assign) NSInteger preClickButtonTag;




@end

@implementation ICMAppointmentMaintenanceAndPartsView

- (NSMutableArray *)delRepairPartsArray{
    if (!_delRepairPartsArray) {
        _delRepairPartsArray = [NSMutableArray array];
    }
    return _delRepairPartsArray;
}
- (NSMutableArray *)delRepairEventArray{
    if (!_delRepairEventArray) {
        _delRepairEventArray = [NSMutableArray array];
    }
    return _delRepairEventArray;
}


- (NSMutableArray *)repairTypes{
    if (!_repairTypes) {
        _repairTypes = [NSMutableArray array];
    }
    return _repairTypes;
}

- (NSMutableArray *)repairEventArray{
    if (!_repairEventArray) {
        _repairEventArray = [NSMutableArray array];
    }
    return _repairEventArray;
}

- (NSMutableArray *)repairPartsArray{
    if (!_repairPartsArray) {
        _repairPartsArray = [NSMutableArray array];
    }
    return _repairPartsArray;
}

#pragma mark    初始化
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self){
        TPKeyboardAvoidingScrollView *backgroundScrollView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        backgroundScrollView.backgroundColor = [UIColor clearColor];
        backgroundScrollView.showsVerticalScrollIndicator = NO;
        backgroundScrollView.bounces = NO;
        backgroundScrollView.contentSize = CGSizeMake(frame.size.width, ActualHeight(695));
        [self addSubview:backgroundScrollView];
        self.backgroundScrollView = backgroundScrollView;
        
        //        self.repairEventArray = [NSMutableArray arrayWithObjects:[ICMRepairMaintenanceModel fakeData], [ICMRepairMaintenanceModel fakeData], [ICMRepairMaintenanceModel fakeData], nil];
        //        self.repairPartsArray = [NSMutableArray arrayWithObjects:[ICMRepairPartsModel fakeData], [ICMRepairPartsModel fakeData], [ICMRepairPartsModel fakeData], nil];
        [self setupAllPriceView];
        [self setupRepairTypeView];
        
        
        UIView *thirdSeperator = [[UIView alloc] initWithFrame:CGRectMake(xInset, self.repairPartsTableView.bottomEdge+ActualHeight(25), ScreenWidth-2*xInset, 1.0)];
        thirdSeperator.backgroundColor = SepColor_gray;
        [backgroundScrollView addSubview:thirdSeperator];
        
//        ICMTitleTextFeildView *finishTimeView = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(xInset, thirdSeperator.bottomEdge+ActualHeight(25), ActualWidth(220), ActualHeight(63)) title:@"预计交车时间" addTarget:nil selector:nil];
//        [backgroundScrollView addSubview:finishTimeView];
//        self.finishTimeView = finishTimeView;
//        
//        UIView *fourthSeperator = [[UIView alloc] initWithFrame:CGRectMake(xInset, finishTimeView.bottomEdge+ActualHeight(25), ScreenWidth-2*xInset, 1.0)];
//        fourthSeperator.backgroundColor = SepColor_gray;
//        [backgroundScrollView addSubview:fourthSeperator];
        
        self.backgroundColor = BackgroundColor_White;
        
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
        tapGestureRecognizer.cancelsTouchesInView = NO;
        [self addGestureRecognizer:tapGestureRecognizer];
    }
    return self;
}

#pragma mark    设置上方输入框
- (void)setupAllPriceView{
    //第一行
    ICMTitleTextFeildView *workingUnitPriceView = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(xInset, yDistance, ActualWidth(220), TitleTFViewHeight) title:@"工时单价"];
    workingUnitPriceView.contentText = self.SERIES_LABOUR_PRICE;
    if([ICrEAMTool isVW]){
        workingUnitPriceView.hidden = YES;
    }else{
        workingUnitPriceView.hidden = NO;
    }
    
    [self.backgroundScrollView addSubview:workingUnitPriceView];
    
    ICMTitleTextFeildView *workingPriceView = [ICMTitleTextFeildView createEditableICMTitleTextFeildViewWithFrame:CGRectMake(workingUnitPriceView.rightEdge+xDistance, workingUnitPriceView.y, ActualWidth(220), TitleTFViewHeight) title:@"工时费"];
    workingPriceView.contentText = @"0.00";
    workingPriceView.contentTextFeild.keyboardType = UIKeyboardTypeDecimalPad;
    workingPriceView.contentTextFeild.delegate = self;
    [self.backgroundScrollView addSubview:workingPriceView];
    
    ICMTitleTextFeildView *partsPriceView = [ICMTitleTextFeildView createEditableICMTitleTextFeildViewWithFrame:CGRectMake(workingPriceView.rightEdge+xDistance, workingPriceView.y, ActualWidth(220), TitleTFViewHeight) title:@"零件费"];
    partsPriceView.contentText = @"0.00";
    partsPriceView.contentTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    partsPriceView.contentTextFeild.delegate = self;
    [self.backgroundScrollView addSubview:partsPriceView];
    
    ICMTitleTextFeildView *totalPriceView = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(partsPriceView.rightEdge+xDistance, partsPriceView.y, ActualWidth(220), TitleTFViewHeight) title:@"总金额"];
    totalPriceView.contentText = @"0.00";
    totalPriceView.contentTextFeild.keyboardType = UIKeyboardTypeDecimalPad;
    totalPriceView.contentTextFeild.delegate = self;
    [self.backgroundScrollView addSubview:totalPriceView];
    
    self.workingUnitPriceView = workingUnitPriceView;
    self.workingPriceView = workingPriceView;
    self.partsPriceView = partsPriceView;
    self.totalPriceView = totalPriceView;
    
    //第二行
    ICMTitleTextFeildView *workingRatioView = [ICMTitleTextFeildView createEditableICMTitleTextFeildViewWithFrame:CGRectMake(workingPriceView.x, workingPriceView.bottomEdge+yDistance, ActualWidth(220), TitleTFViewHeight) title:@"工时折扣率"];
    workingRatioView.contentText = @"1.00";
    workingRatioView.contentTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    workingRatioView.contentTextFeild.delegate = self;
    [self.backgroundScrollView addSubview:workingRatioView];
    
    ICMTitleTextFeildView *partsRatioView = [ICMTitleTextFeildView createEditableICMTitleTextFeildViewWithFrame:CGRectMake(workingRatioView.rightEdge+xDistance, workingRatioView.y, ActualWidth(220), TitleTFViewHeight) title:@"零件折扣率"];
    partsRatioView.contentText = @"1.00";
    partsRatioView.contentTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    partsRatioView.contentTextFeild.delegate = self;
    [self.backgroundScrollView addSubview:partsRatioView];
    
    ICMTitleTextFeildView *discountedPrice = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(partsRatioView.rightEdge+xDistance, partsRatioView.y, ActualWidth(220), TitleTFViewHeight) title:@"折后总金额"];
    discountedPrice.contentText = @"0.00";
    discountedPrice.contentTextFeild.keyboardType = UIKeyboardTypeDecimalPad;
    discountedPrice.contentTextFeild.delegate = self;
    [self.backgroundScrollView addSubview:discountedPrice];
    
    self.workingRatioView = workingRatioView;
    self.partsRatioView = partsRatioView;
    self.discountedPrice = discountedPrice;
    
}

#pragma mark    设置维修类型的按钮
- (void)resetRepairTypeButtonWithTag:(NSInteger)tag {
    for (UIView *subView in self.repairTypeSelectionView.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            [subView removeFromSuperview];
        }
    }
    
    for (int i = 0; i < self.repairTypes.count; i++) {
        if (i == tag-20010) {
            UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            typeButton.frame = CGRectMake(i*ActualWidth(94)+(i+1)*xInset, yDistance, ActualWidth(94), ActualHeight(30));
            [typeButton setTitle:self.repairTypes[i] forState:UIControlStateNormal];
            [typeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [typeButton setBackgroundColor:TitleColor];
            typeButton.titleLabel.font = TitleFont;
            typeButton.tag = 20010+i;
            [typeButton addTarget:self action:@selector(clickRepairTypeButton:) forControlEvents:UIControlEventTouchUpInside];
            [self.repairTypeSelectionView addSubview:typeButton];
        } else {
            UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            typeButton.frame = CGRectMake(i*ActualWidth(94)+(i+1)*xInset, yDistance, ActualWidth(94), ActualHeight(30));
            [typeButton setTitle:self.repairTypes[i] forState:UIControlStateNormal];
            [typeButton setTitleColor:ContentTextColor_Gray forState:UIControlStateNormal];
            [typeButton setBackgroundColor:[UIColor clearColor]];
            typeButton.titleLabel.font = TitleFont;
            typeButton.tag = 20010+i;
            [typeButton addTarget:self action:@selector(clickRepairTypeButton:) forControlEvents:UIControlEventTouchUpInside];
            [self.repairTypeSelectionView addSubview:typeButton];
        }
    }

}

- (void)resetRepairTypeButton {
    [self resetRepairTypeButtonWithTag:20010];
    [self.repairEventTableView reloadData];
    [self.repairPartsTableView reloadData];
}

#pragma mark    设置按钮状态
- (void)setupRepairTypeView {
    UIView *repairTypeSelectionView = [[UIView alloc] initWithFrame:CGRectMake(0, self.workingRatioView.bottomEdge+ActualHeight(30), ScreenWidth, ActualHeight(55))];
    repairTypeSelectionView.backgroundColor = BackgroundColor_White;
    [self.backgroundScrollView addSubview:repairTypeSelectionView];
    self.repairTypeSelectionView = repairTypeSelectionView;
    
    for (int i = 0; i < self.repairTypes.count; i++) {
        if (i == 0) {
            UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            typeButton.frame = CGRectMake(i*ActualWidth(94)+(i+1)*xInset, yDistance, ActualWidth(94), ActualHeight(30));
            [typeButton setTitle:self.repairTypes[i] forState:UIControlStateNormal];
            [typeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [typeButton setBackgroundColor:TitleColor];
            typeButton.titleLabel.font = TitleFont;
            typeButton.tag = 20010+i;
            [typeButton addTarget:self action:@selector(clickRepairTypeButton:) forControlEvents:UIControlEventTouchUpInside];
            [self.repairTypeSelectionView addSubview:typeButton];
        } else {
            UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            typeButton.frame = CGRectMake(i*ActualWidth(94)+(i+1)*xInset, yDistance, ActualWidth(94), ActualHeight(30));
            [typeButton setTitle:self.repairTypes[i] forState:UIControlStateNormal];
            [typeButton setTitleColor:ContentTextColor_Gray forState:UIControlStateNormal];
            [typeButton setBackgroundColor:[UIColor clearColor]];
            typeButton.titleLabel.font = TitleFont;
            typeButton.tag = 20010+i;
            [typeButton addTarget:self action:@selector(clickRepairTypeButton:) forControlEvents:UIControlEventTouchUpInside];
            [self.repairTypeSelectionView addSubview:typeButton];
        }
    }
    
    UIView *firstSeperator = [[UIView alloc] initWithFrame:CGRectMake(xInset, 0, ScreenWidth-2*xInset, 1.0)];
    firstSeperator.backgroundColor = SepColor_gray;
    [repairTypeSelectionView addSubview:firstSeperator];
    
    UIView *secondSeperator = [[UIView alloc] initWithFrame:CGRectMake(firstSeperator.x, repairTypeSelectionView.height-2, firstSeperator.width, 1.0)];
    secondSeperator.backgroundColor = SepColor_gray;
    [repairTypeSelectionView addSubview:secondSeperator];
    
    [self setupRepairEventHeaderView];
    
    UITableView *repairEventTableView = [[UITableView alloc] initWithFrame:CGRectMake(xInset, repairTypeSelectionView.bottomEdge+yDistance+ActualHeight(25), ScreenWidth-xInset*2, ActualHeight(100))];
    self.repairEventTableView = repairEventTableView;
    repairEventTableView.delegate = self;
    repairEventTableView.dataSource = self;
    repairEventTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [repairEventTableView registerClass:[ICMGetCarRepairEventTableViewCell class] forCellReuseIdentifier:@"repairEventCell"];
    repairEventTableView.backgroundColor = [UIColor clearColor];
    repairEventTableView.tableFooterView = [[UIView alloc] init];
    [self.backgroundScrollView addSubview:repairEventTableView];
    
    [self setupRepairPartsHeaderView];
    
    UITableView *repairPartsTableView = [[UITableView alloc] initWithFrame:CGRectMake(xInset, repairTypeSelectionView.bottomEdge+ActualHeight(180), ScreenWidth-xInset*2, ActualHeight(100))];
    self.repairPartsTableView = repairPartsTableView;
    repairPartsTableView.delegate = self;
    repairPartsTableView.dataSource = self;
    repairPartsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [repairPartsTableView registerClass:[ICMGetCarRepairPartsTableViewCell class] forCellReuseIdentifier:@"repairPartsCell"];
    repairPartsTableView.backgroundColor = [UIColor clearColor];
    repairPartsTableView.tableFooterView = [[UIView alloc] init];
    [self.backgroundScrollView addSubview:repairPartsTableView];
}

#pragma mark    维修项目头部
- (void)setupRepairEventHeaderView{
    UIView *repairEventHeadView = [[UIView alloc] initWithFrame:CGRectMake(xInset, self.repairTypeSelectionView.bottomEdge+yDistance, ScreenWidth-xInset*2, ActualHeight(25))];
    repairEventHeadView.backgroundColor = TitleColor;
    
    UILabel *operateLabel = [self createLabelWithText:@"操作" frame:CGRectMake(0, ActualHeight(5), ActualWidth(50), ActualHeight(15))];
    [repairEventHeadView addSubview:operateLabel];
    
    UIView *firstSep = [[UIView alloc] initWithFrame:CGRectMake(operateLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    firstSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:firstSep];
    
    UILabel *orderLabel = [self createLabelWithText:@"序号" frame:CGRectMake(firstSep.rightEdge, operateLabel.y, ActualWidth(50), ActualHeight(15))];
    [repairEventHeadView addSubview:orderLabel];
    
    UIView *secondSep = [[UIView alloc] initWithFrame:CGRectMake(orderLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    secondSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:secondSep];
    
    UILabel *eventNumberLabel = [self createLabelWithText:@"项目代码" frame:CGRectMake(secondSep.rightEdge, operateLabel.y, ActualWidth(145), ActualHeight(15))];
    [repairEventHeadView addSubview:eventNumberLabel];
    
    UIView *thirdSep = [[UIView alloc] initWithFrame:CGRectMake(eventNumberLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    thirdSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:thirdSep];
    
    UILabel *eventNameLabel = [self createLabelWithText:@"项目名称" frame:CGRectMake(thirdSep.rightEdge, operateLabel.y, ActualWidth(215), ActualHeight(15))];
    [repairEventHeadView addSubview:eventNameLabel];
    
    UIView *fourthSep = [[UIView alloc] initWithFrame:CGRectMake(eventNameLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    fourthSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:fourthSep];
    
    UILabel *workingTimeLabel = [self createLabelWithText:@"执行工时" frame:CGRectMake(fourthSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    
    [repairEventHeadView addSubview:workingTimeLabel];
    
    UIView *fifthSep = [[UIView alloc] initWithFrame:CGRectMake(workingTimeLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    fifthSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:fifthSep];
    
    UILabel *priceLabel = [self createLabelWithText:@"工时单价" frame:CGRectMake(fifthSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairEventHeadView addSubview:priceLabel];
    
    UIView *priceSep = [[UIView alloc] initWithFrame:CGRectMake(priceLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    priceSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:priceSep];
    
    UILabel *workingPriceLabel = [self createLabelWithText:@"工时费" frame:CGRectMake(priceSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairEventHeadView addSubview:workingPriceLabel];
    
    UIView *sixthSep = [[UIView alloc] initWithFrame:CGRectMake(workingPriceLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    sixthSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:sixthSep];
    
    UILabel *repairTypeLabel = [self createLabelWithText:@"维修类型" frame:CGRectMake(sixthSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairEventHeadView addSubview:repairTypeLabel];
    
    UIView *seventhSep = [[UIView alloc] initWithFrame:CGRectMake(repairTypeLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    seventhSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:seventhSep];
    
    UILabel *breakdownDiscribeLabel = [self createLabelWithText:@"故障描述" frame:CGRectMake(seventhSep.rightEdge, operateLabel.y, repairEventHeadView.width-repairTypeLabel.rightEdge, ActualHeight(15))];
    [repairEventHeadView addSubview:breakdownDiscribeLabel];
    
    [self.backgroundScrollView addSubview:repairEventHeadView];
}

#pragma mark    维修零件头部
- (void)setupRepairPartsHeaderView{
    UIView *repairPartsHeadView = [[UIView alloc] initWithFrame:CGRectMake(xInset, self.repairTypeSelectionView.bottomEdge+ActualHeight(155), ScreenWidth-xInset*2, ActualHeight(25))];
    repairPartsHeadView.backgroundColor = TitleColor;
    
    UILabel *operateLabel = [self createLabelWithText:@"操作" frame:CGRectMake(0, ActualHeight(5), ActualWidth(50), ActualHeight(15))];
    [repairPartsHeadView addSubview:operateLabel];
    
    UIView *firstSep = [[UIView alloc] initWithFrame:CGRectMake(operateLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    firstSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:firstSep];
    
    UILabel *orderLabel = [self createLabelWithText:@"序号" frame:CGRectMake(firstSep.rightEdge, operateLabel.y, ActualWidth(50), ActualHeight(15))];
    [repairPartsHeadView addSubview:orderLabel];
    
    UIView *secondSep = [[UIView alloc] initWithFrame:CGRectMake(orderLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    secondSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:secondSep];
    
    UILabel *partNumberLabel = [self createLabelWithText:@"零件代码" frame:CGRectMake(secondSep.rightEdge, operateLabel.y, ActualWidth(145), ActualHeight(15))];
    [repairPartsHeadView addSubview:partNumberLabel];
    
    UIView *thirdSep = [[UIView alloc] initWithFrame:CGRectMake(partNumberLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    thirdSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:thirdSep];
    
    UILabel *partNameLabel = [self createLabelWithText:@"零件名称" frame:CGRectMake(thirdSep.rightEdge, operateLabel.y, ActualWidth(215), ActualHeight(15))];
    [repairPartsHeadView addSubview:partNameLabel];
    
    UIView *fourthSep = [[UIView alloc] initWithFrame:CGRectMake(partNameLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    fourthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:fourthSep];
    
    UILabel *numberLabel = [self createLabelWithText:@"数量" frame:CGRectMake(fourthSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:numberLabel];
    
    UIView *fifthSep = [[UIView alloc] initWithFrame:CGRectMake(numberLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    fifthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:fifthSep];
    
    UILabel *unitPriceLabel = [self createLabelWithText:@"单价" frame:CGRectMake(fifthSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:unitPriceLabel];
    
    UIView *sixthSep = [[UIView alloc] initWithFrame:CGRectMake(unitPriceLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    sixthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:sixthSep];
    
    UILabel *totalPriceLabel = [self createLabelWithText:@"销售金额" frame:CGRectMake(sixthSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:totalPriceLabel];
    
    UIView *seventhSep = [[UIView alloc] initWithFrame:CGRectMake(totalPriceLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    seventhSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:seventhSep];
    
    UILabel *repairTypeLabel = [self createLabelWithText:@"维修类型" frame:CGRectMake(seventhSep.rightEdge, operateLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:repairTypeLabel];
    
    UIView *eighthSep = [[UIView alloc] initWithFrame:CGRectMake(repairTypeLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    eighthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:eighthSep];
    
    UILabel *stockPlaceLabel = [self createLabelWithText:@"库位代码" frame:CGRectMake(eighthSep.rightEdge, operateLabel.y, ActualWidth(105), ActualHeight(15))];
    [repairPartsHeadView addSubview:stockPlaceLabel];
    
    UIView *ninthSep = [[UIView alloc] initWithFrame:CGRectMake(stockPlaceLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    ninthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:ninthSep];
    
    UILabel *partPropertyLabel = [self createLabelWithText:@"零件属性" frame:CGRectMake(ninthSep.rightEdge, operateLabel.y, repairPartsHeadView.width-stockPlaceLabel.rightEdge - ActualWidth(40), ActualHeight(15))];
    [repairPartsHeadView addSubview:partPropertyLabel];
    
    UIView *tenthSep = [[UIView alloc] initWithFrame:CGRectMake(partPropertyLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    tenthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:tenthSep];
    
    UILabel *remainLabel = [self createLabelWithText:@"留存" frame:CGRectMake(tenthSep.rightEdge, operateLabel.y, ActualWidth(40), ActualHeight(15))];
    [repairPartsHeadView addSubview:remainLabel];
    
    [self.backgroundScrollView addSubview:repairPartsHeadView];
}

#pragma mark tableViewDelegateAndDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.repairEventTableView) {
        return self.repairEventArray.count;
    } else if (tableView == self.repairPartsTableView) {
        return self.repairPartsArray.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ActualHeight(25.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.repairEventTableView) {
        ICMGetCarRepairEventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"repairEventCell"];
        if (!cell) {
            cell = [[ICMGetCarRepairEventTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"repairEventCell"];
        }
        cell.order = indexPath.row;
        cell.repairTypes = self.repairTypes;
        cell.delegate = self;
        cell.SERIES_LABOUR_PRICE = self.SERIES_LABOUR_PRICE;
        if (self.repairEventArray.count > indexPath.row) {
            ICMRepairMaintenanceModel *model = self.repairEventArray[indexPath.row];
            model.SERIES_LABOUR_PRICE = self.SERIES_LABOUR_PRICE;
            
            [cell setupLabelsWithModel:model];
        }
        return cell;
    } else if (tableView == self.repairPartsTableView) {
        ICMGetCarRepairPartsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"repairPartsCell"];
        if (!cell) {
            cell = [[ICMGetCarRepairPartsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"repairPartsCell"];
        }
        cell.inType = 0;
        cell.order = indexPath.row;
        cell.repairTypes = self.repairTypes;
        cell.delegate = self;
        if (self.repairPartsArray.count > indexPath.row) {
            [cell setupLabelsWithModel:self.repairPartsArray[indexPath.row]];
        }
        return cell;
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

#pragma mark    维修类型按钮点击
- (void)clickRepairTypeButton:(UIButton *)sender{
    [self endEditing:YES];
    
    if ([self.workingUnitPriceView.contentText floatValue] == 0) {
        [self showString:@"请先维护车系工时单价！" forSeconds:1.5f];
        return;
    }
    NSArray *noRepairs = @[@"召回行动",@"技术活动",@"服务活动"];
    NSString *repairType = self.repairTypes[sender.tag-20010];
    if ([noRepairs containsObject:repairType]) {
        [self showString:[NSString stringWithFormat:@"%@ 不能添加项目和零件",repairType] forSeconds:1.5];
        return;
    }

    if (self.preClickButtonTag != sender.tag) {
        [self resetRepairTypeButtonWithTag:sender.tag];
    }
    
    self.reapsvc = [[ICMRepairEventAndPartSearchViewController alloc] init];
    self.reapsvc.delegate = self;
    self.reapsvc.hasPartLeft = YES;
    
    self.preClickButtonTag = sender.tag;
    self.selectedRepairType = repairType;
    self.reapsvc.view.frame = Window.bounds;
    self.reapsvc.existRepairEventArray = self.repairEventArray;
    self.reapsvc.existRepairPartsArray = self.repairPartsArray;
    self.reapsvc.modelCode = self.modelCode;
    [Window addSubview:self.reapsvc.view];
    if ([self.delegate respondsToSelector:@selector(showRepairEventAndSearchViewWithRepairType:)]) {
        [self.delegate showRepairEventAndSearchViewWithRepairType:repairType];
    }
}

#pragma mark    删除维修项目提示
- (void)deleteRepairEventCellAtIndexPath:(NSIndexPath *)indexPath{
    self.wishDeleteIndex = indexPath.row;
    ICMRepairMaintenanceModel *model = self.repairEventArray[indexPath.row];
    NSString *showString = [NSString stringWithFormat:@"确认删除 \"%@\" 维修项目？",model.LABOUR_CODE];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:showString delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
    alert.tag = 1001;
    [alert show];
}
#pragma mark    删除维修项目
- (void)deleteEvent{
    ICMRepairMaintenanceModel *model = self.repairEventArray[self.wishDeleteIndex];
    if(![model.UPDATE_STATUS isEqualToString:@"A"])
    {
        model.UPDATE_STATUS = @"D";
        [self.delRepairEventArray PACA_AddObject:self.repairEventArray[self.wishDeleteIndex]];
    }
    [self.repairEventArray removeObjectAtIndex:self.wishDeleteIndex];
    [self calculateAll];
    [self.repairEventTableView reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        if (alertView.tag == 1001) {
            [self deleteEvent];
        }else if (alertView.tag == 1002){
            [self deleltePart];
        }
    }
}
#pragma mark    删除维修零件
- (void)deleltePart{
    ICMRepairPartsModel *model = self.repairPartsArray[self.wishDeleteIndex];
    if(![model.UPDATE_STATUS isEqualToString:@"A"])
    {
        model.UPDATE_STATUS = @"D";
        [self.delRepairPartsArray PACA_AddObject:self.repairPartsArray[self.wishDeleteIndex]];
    }
    [self.repairPartsArray removeObjectAtIndex:self.wishDeleteIndex];
    [self calculateAll];
    [self.repairPartsTableView reloadData];
}


- (void)deleteRepairPartsCellAtIndexPath:(NSIndexPath *)indexPath{
    self.wishDeleteIndex = indexPath.row;
    ICMRepairPartsModel *model = self.repairPartsArray[self.wishDeleteIndex];
    NSString *showString = [NSString stringWithFormat:@"确认删除 \"%@\" 维修零件？",model.PART_NO];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:showString delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
    alert.tag = 1002;
    [alert show];
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    float number = [textField.text floatValue];
    textField.text = [NSString stringWithFormat:@"%.2f", number];
    if (textField == self.workingPriceView.contentTextFeild
        ||
        textField == self.partsPriceView.contentTextFeild) {
        self.totalPriceView.contentText = [NSString stringWithFormat:@"%.2f",[self.workingPriceView.contentText floatValue] + [self.partsPriceView.contentText floatValue]];
        float discount = [self.workingPriceView.contentText floatValue]*[self.workingRatioView.contentText floatValue] + [self.partsPriceView.contentText floatValue]*[self.partsRatioView.contentText floatValue];
        self.discountedPrice.contentText = [NSString stringWithFormat:@"%.2f",discount];
    } else if (textField == self.workingRatioView.contentTextFeild
               ||
               textField == self.partsRatioView.contentTextFeild) {
        if([textField.text floatValue] < 0.00f || [textField.text floatValue] > 1.00f)
        {
            [self showString:@"折扣率必须在0到1之间!" forSeconds:1.5];
            textField.text = @"1.00";
            return;
        }
        if (textField == self.workingRatioView.contentTextFeild) {
            for (ICMRepairMaintenanceModel *model in self.repairEventArray) {
                if (model.isDiscount) {
                    model.DISCOUNT = [self.workingRatioView.contentText doubleValue];
                    if(![model.UPDATE_STATUS isEqualToString:@"A"])
                    {
                        model.UPDATE_STATUS = @"U";
                    }
                }
            }
        }else{
            for (ICMRepairPartsModel *model in self.repairPartsArray) {
                model.DISCOUNT = [self.partsRatioView.contentText doubleValue];
                if(![model.UPDATE_STATUS isEqualToString:@"A"])
                {
                    model.UPDATE_STATUS = @"U";
                }
            }
        }
        [self calculateAll];
    }
}


- (void)calculateAll{
    [self calculateSelectedPrice];
    [self calculatePrice];
    [self calculateRatioPrice];
}

#pragma mark    计算选中后的价钱
- (void)calculateSelectedPrice {
    double repairEventPrice = 0.0;
    double repairPartPrice = 0.0;
    
    for (ICMRepairMaintenanceModel *model in self.repairEventArray) {
        if(![model.UPDATE_STATUS isEqualToString:@"D"]){
            if([model.LABOUR_AMOUNT isKindOfClass:[NSString class]])
            {
                repairEventPrice = repairEventPrice+[model.LABOUR_AMOUNT doubleValue];
            }
            
        }
    }
    self.workingPriceView.contentText = self.isPayForType?@"0.00":[NSString stringWithFormat:@"%.2lf", repairEventPrice];
    
    for (ICMRepairPartsModel *model in self.repairPartsArray) {
        if(![model.UPDATE_STATUS isEqualToString:@"D"]){
            repairPartPrice = repairPartPrice+[model.PART_SALES_AMOUNT doubleValue];
        }
    }
    self.partsPriceView.contentText = self.isPayForType?@"0.00":[NSString stringWithFormat:@"%.2lf", repairPartPrice];
    self.totalPriceView.contentText = self.isPayForType?@"0.00":[NSString stringWithFormat:@"%.2lf", repairEventPrice+repairPartPrice];
}

- (void)calculatePrice {
    int workingPrice = [self.workingPriceView.contentText floatValue]*100;
    int partPrice = [self.partsPriceView.contentText floatValue]*100;
    self.totalPriceView.contentText = self.isPayForType?@"0.00":[NSString stringWithFormat:@"%.2f", (workingPrice+partPrice)/100.0];
}
#pragma mark    计算包含折扣率的价钱
- (void)calculateRatioPrice {
    double ratioEventPrice = 0.0;
    double ratioPartPrice = 0.0;
    
    for (ICMRepairMaintenanceModel *model in self.repairEventArray) {
        if(![model.UPDATE_STATUS isEqualToString:@"D"])
        {
            if (model.isDiscount)
            {
                if([model.LABOUR_AMOUNT isKindOfClass:[NSString class]])
                {
                    ratioEventPrice = ratioEventPrice + [model.LABOUR_AMOUNT doubleValue] * model.DISCOUNT;
                }
            }
            else
            {
                if([model.LABOUR_AMOUNT isKindOfClass:[NSString class]])
                {
                    ratioEventPrice += [model.LABOUR_AMOUNT doubleValue];
                }
            }
        }
    }
    
    for (ICMRepairPartsModel *model in self.repairPartsArray) {
        if(![model.UPDATE_STATUS isEqualToString:@"D"])
        {
            ratioPartPrice += [model.PART_SALES_AMOUNT doubleValue] * model.DISCOUNT;
        }
    }
    
    self.discountedPrice.contentText = self.isPayForType?@"0.00":[NSString stringWithFormat:@"%.2f", ratioEventPrice+ratioPartPrice];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    BOOL isHavePoint = YES;
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHavePoint = NO;
    }
    if ([string length]>0)
    {
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([textField.text length] == 0){
                if(single == '.'){
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            if (single == '.')
            {
                if(!isHavePoint)//text中还没有小数点
                {
                    isHavePoint=YES;
                    return YES;
                }else
                {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHavePoint)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    int tt = range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    } else {
                        return NO;
                    }
                } else {
                    return YES;
                }
            }
        } else {//输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    } else {
        return YES;
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
}

- (void)keyboardHide:(UITapGestureRecognizer*)tap{
    
    UIView *firstResponder = [Window performSelector:@selector(firstResponder)];
    [firstResponder resignFirstResponder];
}

#pragma mark    获得选取的维修项目和零件
- (void)getSelectedRepairEvents:(NSMutableArray *)selectedEvents repairParts:(NSMutableArray *)selectedParts{
    
    for (ICMRepairMaintenanceModel *model in selectedEvents) {
        model.REPAIR_TYPE_CODE = [ICrEAMTool getRepiarTypeCodeWithRepiarName:self.selectedRepairType];
        model.REPAIR_TYPE_NAME = self.selectedRepairType;
        //新工时单价（车系工时单价×工位类型系数×技术难度系数）
        model.workingHoursPrice = [self calculateWorkingHoursWithSERIES_LABOUR_PRICE:self.workingUnitPriceView.contentText andREPAIR_ITEM_TYPE_RATE:model.REPAIR_ITEM_TYPE_RATE andTECHNIC_MODULUS:model.TECHNIC_MODULUS];
        
        model.LABOUR_PRICE = model.workingHoursPrice;

        
       
        if (model.isDiscount) {
            model.DISCOUNT = [self.workingRatioView.contentText floatValue];
        } else {
            model.DISCOUNT = 1.0;
        }
    }
    
    for (ICMRepairPartsModel *model in selectedParts) {
        model.IS_DISCOUNT = ICMEnumIntToString(ICMEnumYESOrNONO);
        model.REPAIR_TYPE_CODE = [ICrEAMTool getRepiarTypeCodeWithRepiarName:self.selectedRepairType];
        model.REPAIR_TYPE_NAME = self.selectedRepairType;
        model.DISCOUNT = [self.partsRatioView.contentText floatValue];
        model.REPAIR_TYPE_NAME = self.selectedRepairType;
    }
    
    [self.repairEventArray addObjectsFromArray:selectedEvents];
    [self.repairPartsArray addObjectsFromArray:selectedParts];
    [self calculateAll];
    [self refreshInEditType];
}
-(NSString *)calculateWorkingHoursWithSERIES_LABOUR_PRICE:(NSString *)SERIES_LABOUR_PRICE andREPAIR_ITEM_TYPE_RATE:(NSString *)REPAIR_ITEM_TYPE_RATE andTECHNIC_MODULUS:(NSString *)TECHNIC_MODULUS{
    
    double series_labour_price = [SERIES_LABOUR_PRICE floatValue];
    double repair_item_type_rate = [REPAIR_ITEM_TYPE_RATE floatValue];
    double texhnic_modulus = [TECHNIC_MODULUS floatValue];
    
    double workingHours = series_labour_price * repair_item_type_rate * texhnic_modulus;
    
    NSString *workingHoursStr = [NSString stringWithFormat:@"%.2f",workingHours];
    
    return workingHoursStr;
}

#pragma mark    零件数改变
- (void)didChangePartsQuantitys{
    [self calculateAll];
    [self.repairPartsTableView reloadData];
}
#pragma mark    零件数设置为0
- (void)partsQuantitysWillChangeToZero{
    [self showString:@"配件数量不能为零，请检查!" forSeconds:1.5];
}
#pragma mark    零件选择数量大于实际库存
- (void)quantityNotEnough:(NSString *)message{
    [self showString:message forSeconds:1.5];
}

- (UILabel *)createLabelWithText:(NSString *)text frame:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = TitleFont;
    label.textColor = ContentTextColor_Black;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

#pragma mark    保存成功后需要将所有的零件和项目状态初始化
- (void)setAllStateToInit{
    NSMutableArray *deleteIndexs = [NSMutableArray array];
    for (NSInteger i=0;i<self.repairPartsArray.count;i++) {
        ICMRepairPartsModel *model = self.repairPartsArray[i];
        if ([model.UPDATE_STATUS isEqualToString:@"D"]) {
            [deleteIndexs PACA_AddObject:[@(i) stringValue]];
        }else{
            model.UPDATE_STATUS = nil;
        }
    }
    if (self.repairPartsArray.count) {
        for (NSString *index in deleteIndexs) {
            [self.repairPartsArray removeObjectAtIndex:[index integerValue]];
        }
    }
    [deleteIndexs removeAllObjects];
    for (NSInteger i=0;i<self.repairEventArray.count;i++) {
        ICMRepairMaintenanceModel *model = self.repairEventArray[i];
        if ([model.UPDATE_STATUS isEqualToString:@"D"]) {
            [deleteIndexs PACA_AddObject:[@(i) stringValue]];
        }else{
            model.UPDATE_STATUS = nil;
        }
    }
    if (self.repairEventArray.count) {
        for (NSString *index in deleteIndexs) {
            [self.repairEventArray removeObjectAtIndex:[index integerValue]];
        }
    }
}

+ (instancetype)createICMMaintenanceAndPartsViewWithFrame:(CGRect)frame{
    return [[ICMAppointmentMaintenanceAndPartsView alloc] initWithFrame:frame];
}
#pragma mark    根据输入框model设置界面
- (void)setupPartsViewWithPartsTopModel:(ICMPartsTopModel*)topModel{
    self.workingUnitPriceView.contentText = [NSString stringWithFormat:@"%.2f",[self.SERIES_LABOUR_PRICE floatValue]];
    
    if([topModel.LABOUR_AMOUNT isKindOfClass:[NSString class]])
    {
        self.workingPriceView.contentText = [NSString stringWithFormat:@"%.2f",[topModel.LABOUR_AMOUNT floatValue]];
    }
    else
    {
        self.workingPriceView.contentText = @"0.00";
    }
    self.partsPriceView.contentText = [NSString stringWithFormat:@"%.2f",[topModel.REPAIR_PART_AMOUNT floatValue]];
    self.totalPriceView.contentText = [NSString stringWithFormat:@"%.2f",[topModel.TOTAL_AMOUNT floatValue]];
    //工时折扣率
    if(!topModel.LABOUR_DISCOUNT_RATE || [topModel.LABOUR_DISCOUNT_RATE isEqualToString:@""])
    {
        self.workingRatioView.contentText = @"1.00";
    }
    else
    {
        self.workingRatioView.contentText = [NSString stringWithFormat:@"%.2f",[topModel.LABOUR_DISCOUNT_RATE floatValue]];
    }
    //零件折扣率
    if(!topModel.PART_DISCOUNT_RATE || [topModel.PART_DISCOUNT_RATE isEqualToString:@""])
    {
        self.partsRatioView.contentText = @"1.00";
    }
    else
    {
        self.partsRatioView.contentText = [NSString stringWithFormat:@"%.2f",[topModel.PART_DISCOUNT_RATE floatValue]];
    }
    self.discountedPrice.contentText = [NSString stringWithFormat:@"%.2f",[topModel.RECEIVE_AMOUNT floatValue]];
    
    
    [self calculateAll];
    [self.repairEventTableView reloadData];
}
#pragma mark    根据项目Model设置界面
- (void)setupPartsViewWithRepairMaintenancesModel:(ICMRepairMaintenancesModel*)repairMaintenancesModel{
    self.repairEventArray = repairMaintenancesModel.TT_BOOKING_ORDER_LABOUR;
    [self.repairEventTableView reloadData];
}
#pragma mark    根据零件Model设置界面
- (void)setupPartsViewWithRepairPartsArrayModel:(ICMRepairPartsArrayModel*)repairPartsArrayModel{
    self.repairPartsArray = repairPartsArrayModel.TT_BOOKING_ORDER_PART;
    [self.repairPartsTableView reloadData];
}

- (void)refreshInEditType{
    [self.repairEventTableView reloadData];
    [self.repairPartsTableView reloadData];
}

#pragma mark    isPayForType getter方法
- (BOOL)isPayForType{
    BOOL isPayForType = NO;
    NSArray *payForTypes = @[@"质量担保保养",@"普通索赔",@"PDI 索赔",[ICrEAMTool isVW]?@"优惠索赔":@"优惠维修",@"受控索赔",@"三包维修",@"召回活动",@"技术性服务活动"];
    for (NSString *repairType in self.repairTypes) {
        if ([payForTypes containsObject:repairType]) {
            isPayForType = YES;
        }
    }
    self.partsRatioView.contentTextFeild.userInteractionEnabled = !isPayForType;
    self.workingRatioView.contentTextFeild.userInteractionEnabled = !isPayForType;
    return isPayForType;
}

#pragma mark    setIsPayForType
- (void)setIsPayForType:(BOOL)isPayForType{
    self.partsRatioView.contentTextFeild.userInteractionEnabled = !isPayForType;
    self.workingRatioView.contentTextFeild.userInteractionEnabled = !isPayForType;
    if (isPayForType) {
        self.partsRatioView.contentText = @"1.00";
        self.workingRatioView.contentText = @"1.00";
        [self calculateAll];
    }
}

//- (NSString *)modelCode{
//    NSString *code = [self.carTypeView.contentText componentsSeparatedByString:@"|"].firstObject;
//    _modelCode = code?:@"";
//    return _modelCode;
//}


@end

